using System;
using System.Collections.Generic;
using TDUnit.Common.Resolver;

namespace TDUnit.Common.TestData
{
    public class Row
    {
        readonly List<Column> columns = new List<Column>();
        private PrimaryKeyColumn pkColumn;

        #region Constructors

        public Row(Table table) : this(table, string.Empty) { }

        public Row(Table table, string name)
        {
            if (table == null)
                throw new ArgumentNullException("table");

            Table = table;
            Name = name;
        }

        #endregion

        #region Public properties

        public string Name { get; private set; }

        public Table Table { get; private set; }

        public PrimaryKeyColumn PrimaryKeyColumn
        {
            get
            {
                if(pkColumn == null)
                    pkColumn = new PrimaryKeyColumn(Table.PrimaryKeyColumnName).WithIsAutoIdentity(Table.IsPrimaryKeyAutoIdentity);
                return pkColumn;
            } 
        }

        public Column[] Columns
        {
            get { return columns.ToArray(); }
        }

        #endregion

        #region Public methods

        public Column AddColumn(string name)
        {
           return AddColumn(name, string.Empty, null);
        }

        public Column AddColumn(string name, string value)
        {
            return AddColumn(name, value, null);
        }

        public Column AddColumn(string name, string value, bool? shouldQuote)
        {
            Column c;

            var resolver = new DependencyResolver(Table.TestData);

            if (resolver.ShouldResolve(value))
                c = new DependencyColumn(name, resolver.Resolve(value)).WithShouldQuote(shouldQuote);
            else if (name.Equals(Table.PrimaryKeyColumnName))
            {
                c = new PrimaryKeyColumn(name).WithIsAutoIdentity(Table.IsPrimaryKeyAutoIdentity).WithShouldQuote(shouldQuote).WithValue(value);
                pkColumn = (PrimaryKeyColumn)c;
                return c;
            }
            else
                c = new Column(name).WithValue(value).WithShouldQuote(shouldQuote);

            columns.Add(c);
            return c;
        }

        public Column GetColumn(string columnName)
        {
            if (columnName.Equals(PrimaryKeyColumn.Name))
                return PrimaryKeyColumn;

            foreach (var c in columns)
                if (c.Name.Equals(columnName)) return c;
            return null;
        }

        #endregion
    }
}